<template>
	<view>
		<view>
			<table-title content="缴费表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="租户名称" :value="userMsg.userCompany"></view-item>
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor"></view-item>
				<view-item name="房间号" :value="userMsg.userRoom" :isLast="true"></view-item>
			</view>
			<small-title :isNeed="true" v-if="state==='待申请'" content="选择楼盘"></small-title>
			<view v-if="state==='待申请'" class="small-title">
				<select-lay :zindex="2" :value="tvalBuilding" name="build" :options="datalistBuilding" @selectitem="selectitemBuilding"></select-lay>
			</view>
			<small-title :isNeed="true" v-if="state==='待申请'" content="选择租户"></small-title>
			<view v-if="state==='待申请'" class="small-title">
				<select-lay :value="tvalUser" name="name" :options="datalistUser" @selectitem="selectitemUser"></select-lay>
			</view>
			<small-title :isNeed="true" content="缴费清单"></small-title>
			<view style="margin-left: 20rpx;margin-right: 20rpx;">
				<uni-table border stripe emptyText="暂无更多数据" >
				    <!-- 表头行 -->
				    <uni-tr>
						<uni-th style="width: 50rpx;" align="center">序号</uni-th>
				        <uni-th style="width: 50rpx;" align="center">收费项</uni-th>
				        <uni-th style="width: 50rpx;" align="center">描述</uni-th>
						<uni-th style="width: 50rpx;" align="center">单项总费用</uni-th>
				        <uni-th style="width: 50rpx;" align="center">本月费用</uni-th>
						<uni-th style="width: 50rpx;" align="center">上月费用</uni-th>
						<uni-th style="width: 50rpx;" align="center">滞纳金</uni-th>
						<uni-th v-if="status == 2 || status == -1" style="width: 160rpx;" align="center">操作</uni-th>
				    </uni-tr>
				    <!-- 表格数据行 -->
				    <uni-tr v-for="(item,index) in goodList" :key="index">
				        <uni-td align="center">
							<view style="width: 60rpx;">{{index + 1}}</view>
						</uni-td>
				        <uni-td>
							<view style="width: 150rpx;">
								<textarea style="width: 150rpx;" :auto-height="true" :disabled="status !== 2 && status !== -1" v-model="item.name" @blur="watchItem"></textarea>
							</view>
						</uni-td>
				        <uni-td>
							<view style="width: 150rpx;">
								<textarea style="width: 150rpx;" :auto-height="true" :disabled="status !== 2 && status !== -1" v-model="item.desc" ></textarea>
							</view>
						</uni-td>
						<uni-td>
							<view style="width: 150rpx;">
								<input :disabled="true" type="number" v-model="item.allPrice" />
							</view>
						</uni-td>
						<uni-td>
							<view style="width: 150rpx;">
								<input :disabled="status !== 2 && status !== -1" type="number" v-model="item.curPrice" @blur="calItemAllPrice(index)" />
							</view>
						</uni-td>
						<uni-td>
							<view style="width: 150rpx;">
								<input :disabled="status !== 2 && status !== -1" type="number" v-model="item.lastPrice" @blur="calItemAllPrice(index)" />
							</view>
						</uni-td>
						<uni-td>
							<view style="width: 150rpx;">
								<input :disabled="status !== 2 && status !== -1" type="number" v-model="item.lateFee" @blur="calItemAllPrice(index)" />
							</view>
						</uni-td>
						<uni-td align="center" v-if="status == 2 || status == -1">
							<view v-if="status == 2 || status == -1" style="width: 160rpx;">
								<button style="width: 150rpx;margin-left: 0rpx;font-size: 28rpx;" @click="deleteGoods(index)">删除</button>
							</view>
						</uni-td>
				    </uni-tr>
				</uni-table>
			</view>
			<view class="cost-all">费用合计：{{price}} 元</view>
			<button v-if="status == -1" class="add-button" @click="addGoods()">添加项+</button>
			<view v-if="payType == 1" >
				<small-title :isNeed="true" content="租金到期日期"></small-title>
				<view class="small-title">
					<uni-datetime-picker type="date" :value="endDate" start="" end="" @change="change" :disabled="status !== 2 && status !== -1"></uni-datetime-picker>
				</view>
			</view>
			<small-title v-if="status == 1 || status == 3" content="支付信息截图"></small-title>
			<image v-if="status == 1 || status == 3" class="pay-image" :src="chargeImg" mode="scaleToFill" @tap='chooseImage'></image>
			<small-title content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="status===1" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="bbConfirm(3)">确认已收款</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open">驳回</button>
				</view>
			</view>
			<view v-if="status===2" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="reAddOrder">重新发起缴费</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===-1" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="addOrder">发起缴费</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" type="dialog">
		    <uni-popup-dialog mode="input" message="成功消息" title="请输入驳回理由" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE_2,
		myUploadFile,
		syncGetOrder
	} from "../../../util/network.js"
	import {
		processHistoryList
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				status: -1,
				processFlag:false,
				recordId: -1,
				processNo:'待分配',
				state: '待申请',
				payway: [true, false],                                                            //支付方式
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				
				goodList:[{'goodList':'','desc':'','curPrice':0,'lastPrice':0,'lateFee':0,'allPrice':0}],
				endDate:'',
				payType:0,
				price:0,
				chargeImg:'/static/uploadImg.png',                                     //支付信息截图
				chargeImgId:0,
				nopassReasons:'确认已收到款项',
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'受理','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'办结','time':'2020-03-03 03:33:33'}
				],
				proccessListDefult:[],
				token:'',
				//模拟数据列表
				datalistUserbak: [],
				datalistUser: [],
				//模拟初始数据
				//模拟数据列表
				datalistBuilding: [],
				//模拟初始数据
				tvalBuilding: "value2",
				tvalUser: "",
				rentUserId:-1,
				userRightDetail:'',
			}
		},
		methods: {
			change(value){
				this.endDate = value
				console.log(this.endDate)
			},
			calItemAllPrice(index){
				console.log(index)
				
				this.goodList[index].allPrice = Number(this.goodList[index].curPrice) + Number(this.goodList[index].lastPrice) + Number(this.goodList[index].lateFee)
				this.goodList[index].allPrice = parseFloat(this.goodList[index].allPrice)
				this.goodList[index].allPrice = Math.round(this.goodList[index].allPrice * 100)/100
				this.price = 0
				for (var i = 0; i < this.goodList.length; i++) {
					this.price += Number(this.goodList[i].allPrice)
				}
				this.price = parseFloat(this.price)
				this.price = Math.round(this.price * 100)/100
			},
			watchItem(e){
				console.log('值',e.detail.value)
				if(e.detail.value.trim() == '租金'){
					this.payType = 1
				}
			},
			addGoods(){
				console.log('点击了添加')
				if(this.goodList == null){
					this.goodList = []
				}
				this.goodList.push({'goodList':'','desc':'','curPrice':0,'lastPrice':0,'lateFee':0,'allPrice':0})
			},
			deleteGoods(index){
				if(this.goodList.length <= 1){
					let temp = {'goodList':'','desc':'','curPrice':0,'lastPrice':0,'lateFee':0,'allPrice':0}
					this.$set(this.goodList,index,temp)
					return
				}
				this.goodList.splice(index,1)
				this.price = 0
				for (var i = 0; i < this.goodList.length; i++) {
					this.price += Number(this.goodList[i].allPrice)
				}
				this.price = parseFloat(this.price)
				this.price = Math.round(this.price * 100)/100
			},
			selectitemUser(index, item) {
				console.log(item)
				if (index >= 0) {
					this.tvalUser = item.value;
					let userJson = JSON.parse(item.value)
					this.userMsg.userCompany = userJson.name
					this.userMsg.userBuilding = userJson.title
					this.userMsg.userFloor = userJson.floor
					this.userMsg.userRoom = userJson.houseNumber
					this.rentUserId = userJson.id
				} else {
					this.tvalUser = ""
				}
			},
			selectitemBuilding(index, item) {
				console.log(item)
				if (index >= 0) {
					this.tvalBuilding = item.value;
					this.datalistUser = []
					this.datalistUserbak.forEach(item => {
						if(parseInt(this.tvalBuilding) == JSON.parse(item.value).buildId){
							this.datalistUser.push(item)
						}
					})
				} else {
					this.tvalBuilding = ""
				}
			},
			open() {
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				this.$refs.popup.close()
				if(value == ""){
					uni.showModal({
						content:'理由不能为空',
						showCancel:false
					});
					this.$refs.popup.close()
				}else{
					if(this.userRightDetail.exchangeRent.primeAuth == 5){
						this.nopassReasons = "财务主管驳回，原因：" + value
					}else{
						this.nopassReasons = "财务专员驳回，原因：" + value
					}
					this.bbConfirm(0)
					// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
					// ...
					this.$refs.popup.close()
				}
			},
			chooseImage(){
				console.log("ceshi",this.state)
				if(this.status === 0) {
					uni.chooseImage({
						sourceType: ['album'],
						// #ifdef MP-WEIXIN
						sizeType: ['original'],
						// #endif
						success: (res) => {
							let a = myUploadFile(this.token, res.tempFilePaths[0])
							 a.then((v)=>{
								 this.chargeImgId = v
								 console.log("zuizhongid",this.chargeImgId)
							})
							this.chargeImg = res.tempFilePaths[0];
						}
					})
				}else{
					uni.previewImage({
						current: 0,
						urls: [this.chargeImg]
					})
				}
			},
			
			addOrder(){
				if(this.rentUserId == -1 || this.goodList.length == 0){
					uni.showModal({
						content:'请选择租户并编辑缴费清单',
						showCancel:false
					});
					return 0
				}
				for (var i = 0; i < this.goodList.length; i++) {
					if(this.goodList[i].name == null || this.goodList[i].name.trim() == ''){
						uni.showModal({
							content:'缴费项名称不能为空',
							showCancel:false
						});
						return 0
					}
					if(this.goodList[i].allPrice <= 0){
						uni.showModal({
							content:'缴费项金额不能小于等于0元',
							showCancel:false
						});
						return 0
					}
					if(this.goodList[i].curPrice <= 0){
						uni.showModal({
							content:'缴费项金额不能小于等于0元',
							showCancel:false
						});
						return 0
					}
				}
				if(this.payType == 0){
					this.endDate = '2000-01-01'
				}
				if(this.userRightDetail.exchangeRent.primeAuth == 5){
					this.nopassReasons = "财务主管发起缴费通知"
				}else{
					this.nopassReasons = "财务专员发起缴费通知"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/payment-notice/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						itemList:JSON.stringify(this.goodList),
						leaseTime:this.endDate + " 23:59:59",
						payType:parseInt(this.payType),
						price:Number(this.price),
						userId:parseInt(this.rentUserId),
						commentMsg: this.nopassReasons,                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起缴费成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起缴费调用失败")
					}
				})
			},
			
			reAddOrder(){
				if(this.goodList.length == 0){
					uni.showModal({
						content:'请编辑缴费清单',
						showCancel:false
					});
					return 0
				}
				for (var i = 0; i < this.goodList.length; i++) {
					if(this.goodList[i].name == null || this.goodList[i].name.trim() == ''){
						uni.showModal({
							content:'缴费项名称不能为空',
							showCancel:false
						});
						return 0
					}
					if(this.goodList[i].allPrice <= 0){
						uni.showModal({
							content:'缴费项金额不能小于等于0元',
							showCancel:false
						});
						return 0
					}
					if(this.goodList[i].curPrice <= 0){
						uni.showModal({
							content:'缴费项金额不能小于等于0元',
							showCancel:false
						});
						return 0
					}
				}
				if(this.payType == 0){
					this.endDate = '2000-01-01'
				}
				if(this.userRightDetail.exchangeRent.primeAuth == 5){
					this.nopassReasons = "财务主管重新发起缴费通知"
				}else{
					this.nopassReasons = "财务专员重新发起缴费通知"
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/payment-notice/re-add/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						itemList:JSON.stringify(this.goodList),
						leaseTime:this.endDate + " 23:59:59",
						payType:parseInt(this.payType),
						price:Number(this.price),
						commentMsg: this.nopassReasons                      //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("重新发起缴费成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("重新发起缴费调用失败")
					}
				})
			},
			
			bbConfirm(status){
				console.log("[info]","缴费确认：" + this.recordId)
				if(status == 3){
					if(this.userRightDetail.exchangeRent.primeAuth == 5){
						this.nopassReasons = "财务主管确认已收到款项"
					}else{
						this.nopassReasons = "财务专员确认已收到款项"
					}
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/payment-notice/bb-confirm/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						status:status,
						commentMsg: this.nopassReasons,                       //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("缴费确认成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("缴费确认调用失败")
					}
				})
			},
			
			getOrder(){
				let a = syncGetOrder("payment-notice/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 this.status = parseInt(res.data.data.status)
						 switch(this.status) {
						      case 0:
						         this.state = "待用户确认"
						         break;
						      case 1:
						         this.state = "待财务收款"
						         break;
						 	 case 2:
						         this.state = "待财务提交"
						 	    break;
						 	 case 3:
						         this.state = "已缴费办结"
						 	    break;
						      default:
						         this.state = "待申请"
						 } 
						 this.processNo = res.data.data.processNo
						 this.userMsg.userCompany = res.data.data.createUserInfo.name
						 this.userMsg.userBuilding = res.data.data.createUserInfo.title
						 this.userMsg.userFloor = res.data.data.createUserInfo.floor
						 this.userMsg.userRoom = res.data.data.createUserInfo.houseNumber
						 this.goodList = JSON.parse(res.data.data.itemList)
						 this.payType = res.data.data.payType
						 this.price = res.data.data.price
						 try{
						 	 this.endDate = res.data.data.leaseTime.replace('T', ' ')
						 }catch(e){
						 	//TODO handle the exception
						 }
						 if(res.data.data.chargeImgId > 0){
							 this.chargeImgId = res.data.data.chargeImgId
							 this.chargeImg = ONLINE_SERVER_ADDRESS_BASE_2 + '/file/preview/' + this.chargeImgId
						 }
						 this.proccessListDefult=processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
					}
				})
			},
			getUserList(){
				let _this = this
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/user/list`,
					header: {
						'Authorization': this.token,
					},
					data: {
						pageNo:0,
						pageSize:100,
					},
					method:'GET',
					success: function (res) {
						console.log("查询租户",res);
						if(res.data.code == 200){
							let resList = res.data.data.userList
							resList.forEach((item,key) => {
								let temp = {label: "",value: ""}
								temp.label = item.name + '(' + item.houseNumber + ')'
								temp.value = JSON.stringify(item)
								_this.datalistUserbak.push(temp)
								_this.getBuildingList(item)
							});
							_this.$forceUpdate()
						}
					},
					fail: (res) => {
						console.log("查询租户失败")
					}
				})
			},
			getBuildingList(item){
				let flag = true
				for (var i = 0; i < this.datalistBuilding.length; i++) {
					if(this.datalistBuilding[i].value == item.buildId){
						flag = false
						break
					}
				}
				if(flag){
					let temp = {}
					temp.label = item.title
					temp.value = item.buildId
					this.datalistBuilding.push(temp)
				}
			},
			back(){
				uni.navigateBack()
			},
		},
		onLoad(option) {
			//传入单号
			this.recordId = option.id
			this.token = uni.getStorageSync('token')
			this.state = option.state
			this.userRightDetail = uni.getStorageSync("userRight")
		},
		mounted() {
			//如果是新建表单则不查询
			if(this.state != '待申请'){
				this.getOrder()
			}else{
				this.status = -1
				this.getUserList()
			}
		}
	}
</script>

<style>
	page{
		background-color: #ffffff
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
		width: 87%;
	}
	.cost-all{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.pay-image{
		border:2rpx solid;
		border-radius: 2px;
		margin: 0rpx 0 0rpx 50rpx;
		width: 126rpx;
		height: 126rpx;
	}
</style>
